import React, { useState, useEffect } from 'react'
import { message, Select } from 'antd'
import PropTypes from 'prop-types'
import { getCaseArbitratorList } from './ajax'
import { awaitWrap } from '@js/tool'

const { Option } = Select

// 初始化选项数据
async function initArbitratorOptions (caseid, setOptions) {
  const [e, d] = await awaitWrap(getCaseArbitratorList(caseid))
  if (e) {
    return message.warning(e.message)
  }
  setOptions(d)
}

// 改变仲裁员回调
function onChangeHandle (v, options, onChange) {
  const ids = options.map(li => li.id)
  const isArray = v instanceof Array
  let res
  if (isArray) {
    res = []
    v.forEach(id => {
      const index = ids.indexOf(id)
      if (index !== -1) {
        res.push(options[index])
      }
    })
  } else {
    const index = ids.indexOf(v)
    if (index !== -1) {
      res = options[index]
    }
  }
  onChange(res)
}

// 格式化值
function formatValue (value, setV) {
  if (!value) {
    return setV(undefined)
  }
  if (value instanceof Array) {
    const res = value.map(li => li.id)
    return setV(res)
  }
  if (typeof value === 'object') {
    return setV(value.id)
  }
}

function Main ({ caseid, mode, value, onChange }) {
  const [v, setV] = useState(undefined)
  const [options, setOptions] = useState([])
  useEffect(() => {
    if (caseid) {
      initArbitratorOptions(caseid, setOptions)
    }
  }, [caseid])
  useEffect(() => {
    formatValue(value, setV)
  }, [value])
  return (
    <Select placeholder='请选择' value={v} mode={mode} onChange={v => onChangeHandle(v, options, onChange)}>
      {options.map(li => {
        return (
          <Option value={li.id} key={li.id}>{li.name}</Option>
        )
      })}
    </Select>
  )
}

Main.propTypes = {
  caseid: PropTypes.string,
  mode: PropTypes.string,
  value: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
  onChange: PropTypes.func
}
Main.defaultProps = {
  caseid: undefined,
  mode: undefined,
  value: undefined,
  onChange: data => {}
}

export default Main
